/*
    WiiCade Wii Remote API v2.0 
    Copyright (C) 2007 Jerason Banes

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.
    
    It is understood that no reaonable library system exists for Flash
    programs. To that end, this library is considered to be in library
    form when distributed as a source code package for linking to 
    Flash and Actionscript programs. Similarly, static linking of the
    library is understood to be the preferred form of distributing
    the library in binary form.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/

import mx.events.EventDispatcher;

import com.wiicade.*;

class Nunchuk
{
    static public var BUTTON_C:Number = 0x02;
    static public var BUTTON_Z:Number = 0x01;
    
    private var pressed:Number = 0;
    private var stickx:Number = 0;
    private var sticky:Number = 0;
        
    private var parent:WiiRemote;
        
    public var addEventListener:Function;
    public var removeEventListener:Function;
    public var dispatchEvent:Function;
    
    function Nunchuk(parent:WiiRemote)
    {
        this.parent = parent;
        
        EventDispatcher.initialize(this);
    }
    
    public function isDown(buttonCode):Boolean
    {
        return ((this.pressed & buttonCode) > 0);
    }
    
    public function getStickX():Number
    {
        return this.stickx;
    }
    
    public function getStickY():Number
    {
        return this.sticky;
    }
    
    ///// Update Functions \\\\\
    
    function updateButtons(buttons:Number):Void
    {
        var mask = 1;
        var oldpressed = this.pressed;
        var diff;
        
        this.pressed = buttons;
        
        diff = this.pressed ^ oldpressed;

        for(var i=0; i<10; i++)
        {
             if((diff & mask) > 0)
             {
                 if((this.pressed & mask) > 0) dispatchEvent({type:"buttondown", buttonCode: mask, identity: parent.getIdentity()});
                 else dispatchEvent({type:"buttonup", buttonCode: mask, identity: parent.getIdentity()});
             }

             mask <<= 1;
        }
    }
    
    function updateStick(x:Number, y:Number):Void
    {
        this.stickx = x;
        this.sticky = y;
    }
}
